package com.wengyingjian.weixin.alimama;

import com.taobao.api.ApiException;
import com.taobao.api.DefaultTaobaoClient;
import com.taobao.api.TaobaoClient;
import com.taobao.api.domain.NTbkItem;
import com.taobao.api.request.TbkItemInfoGetRequest;
import com.taobao.api.response.TbkItemInfoGetResponse;
import com.wengyingjian.weixin.common.model.TbkItemInfo;
import org.apache.commons.collections4.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Created by hzwengyingjian on 16/12/27.
 */
@Service
public class TopService {

    private static final String tbk_server_url = "http://gw.api.taobao.com/router/rest";

    private String appkey = "23578122";

    private String secret = "07774c84b5009335cf281e74c0a22f01";

    private Logger logger = LoggerFactory.getLogger(this.getClass());

    /**
     * 获取商品的标题
     * 
     * @param url
     * @return null if item not exists
     * @throws ApiException
     */
    public String getItemTitle(String url) throws ApiException {
        logger.info("TopService.getItemTitle url={}", url);
        String numIid = getNumIid(url);
        TaobaoClient client = new DefaultTaobaoClient(tbk_server_url, appkey, secret);
        TbkItemInfoGetRequest req = new TbkItemInfoGetRequest();
        req.setFields("title");
        req.setPlatform(1L);
        req.setNumIids(numIid);
        TbkItemInfoGetResponse rsp = client.execute(req);
        List<NTbkItem> items = rsp.getResults();
        if (CollectionUtils.isEmpty(items)) {
            logger.info("TopService.getItemTitlef failed,return {}", numIid);
            return numIid;
        }
        String title = items.get(0).getTitle();
        logger.info("TopService.getItemTitle:url={},title={}", url, title);
        return title;
    }

    private String getNumIid(String url) {
        // /"id=\\d"
        String reg = "id=\\d++";
        Pattern pattern = Pattern.compile(reg);
        Matcher matcher = pattern.matcher(url);
        if (matcher.find()) {
            String id_num = matcher.group();
            return id_num.replace("id=", "");
        }
        return null;
    }

    public static void main(String[] args) {
        String url = "https://item.taobao.com/item.htm?spm=a230r.1.14.258.ZZvWHk&id=537260399809&ns=1&abbucket=13#detail";
        String nummid = new TopService().getNumIid(url);
        System.out.println("nummid=" + nummid);
    }
}
